package com.example.system.information.log;

import android.content.Context;
import android.util.Log;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MQClientUtil {
    private static final String TAG = "MQClientUtil";
    private static MQClientUtil instance;
    private MqttAndroidClient mqttAndroidClient;
    private Context context;
    private String serverUri;
    private String clientId;
    private String subscriptionTopic;
    private LogProcessor logProcessor;

    private String massString = "{\n" +
            "  \"requestId\": \"test_req_001\",\n" +
            "  \"logTypes\": [\"error\", \"network\"],\n" +
            "  \"timeRange\": {\n" +
            "    \"startTime\": 1753728000000,  // 2023-07-28 00:00:00\n" +
            "    \"endTime\": 1753814399999    // 2023-07-29 00:00:00\n" +
            "  },\n" +
            "  \"timeout\": 30,\n" +
            "  \"maxCount\": 50,\n" +
            "  \"responseTopic\": \"app_log_response_topic\"\n" +
            "}";

    private MQClientUtil(Context context) {
        this.context = context.getApplicationContext();
        logProcessor = new LogProcessor(context);

        processLogMessage(massString);
    }

    public static MQClientUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (MQClientUtil.class) {
                if (instance == null) {
                    instance = new MQClientUtil(context);
                }
            }
        }
        return instance;
    }

    // 初始化MQTT客户端
    public void init(String serverUri, String clientId, String subscriptionTopic) {
        this.serverUri = serverUri;
        this.clientId = clientId;
        this.subscriptionTopic = subscriptionTopic;

        mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                Log.d(TAG, "连接完成: " + serverURI);
                if (reconnect) {
                    Log.d(TAG, "重新订阅主题");
                    subscribeToTopic();
                }
            }

            @Override
            public void connectionLost(Throwable cause) {
                Log.e(TAG, "连接丢失: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                Log.d(TAG, "收到消息: " + new String(message.getPayload()));
                processLogMessage(new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                Log.d(TAG, "消息发送完成");
            }
        });

        connect();
    }

    // 连接到MQTT服务器
    private void connect() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(true);

        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(TAG, "连接成功");
                    subscribeToTopic();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.e(TAG, "连接失败: " + exception.getMessage());
                }
            });
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }

    // 订阅主题
    private void subscribeToTopic() {
        try {
            mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(TAG, "订阅成功");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.e(TAG, "订阅失败: " + exception.getMessage());
                }
            });
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }

    // 处理接收到的日志请求消息
    private void processLogMessage(String message) {
        try {
            JSONObject requestJson = new JSONObject(message);
            String requestId = requestJson.getString("requestId");
            JSONArray logTypes = requestJson.getJSONArray("logTypes");
            JSONObject timeRange = requestJson.getJSONObject("timeRange");
            long startTime = timeRange.getLong("startTime");
            long endTime = timeRange.getLong("endTime");
            int timeout = requestJson.getInt("timeout");
            int maxCount = requestJson.getInt("maxCount");
            String responseTopic = requestJson.getString("responseTopic");

            // 调用日志处理器获取日志数据
            JSONObject logData = logProcessor.getLogData(requestId, logTypes, startTime, endTime, maxCount);

            Log.d(TAG, "白泉==========》: " + logData.toString());

            // 发送日志数据到响应主题
//            publishMessage(responseTopic, logData.toString());
        } catch (JSONException e) {
            Log.e(TAG, "解析消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 发布消息到MQTT服务器
    public void publishMessage(String topic, String message) {
        try {
            if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {
                MqttMessage mqttMessage = new MqttMessage();
                mqttMessage.setPayload(message.getBytes());
                mqttAndroidClient.publish(topic, mqttMessage);
                Log.d(TAG, "发布消息到主题: " + topic);
            } else {
                Log.e(TAG, "MQTT客户端未连接");
            }
        } catch (MqttException e) {
            Log.e(TAG, "发布消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 断开MQTT连接
    public void disconnect() {
        try {
            if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {
                mqttAndroidClient.disconnect();
                Log.d(TAG, "MQTT连接已断开");
            }
        } catch (MqttException e) {
            Log.e(TAG, "断开连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
